package com.example.backed.controller;

import com.example.backed.common.ApiResponse;
import com.example.backed.dto.UserUpdateRequest;
import com.example.backed.entity.User;
import com.example.backed.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Tag(name = "管理员", description = "管理员相关接口")
@RestController
@RequestMapping("/api/admin")
@RequiredArgsConstructor
@Slf4j
@PreAuthorize("hasAuthority('ROLE_ADMIN')")
public class AdminController {
    
    private final UserService userService;
    
    @Operation(summary = "获取用户列表")
    @GetMapping("/users")
    public ApiResponse<Map<String, Object>> getUsers(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String query,
            @RequestParam(required = false) String role,
            @RequestParam(required = false) String status) {
        
        log.info("获取用户列表: page={}, size={}, query={}, role={}, status={}", page, size, query, role, status);
        
        List<User> users = userService.getUserList(page, size, query, role, status);
        int totalCount = userService.countUsers(query, role, status);
        
        Map<String, Object> result = new HashMap<>();
        result.put("content", users);
        result.put("totalElements", totalCount);
        result.put("totalPages", (int) Math.ceil((double) totalCount / size));
        result.put("size", size);
        result.put("number", page);
        
        return ApiResponse.success(result);
    }
    
    @Operation(summary = "更新用户信息")
    @PutMapping("/users/{id}")
    public ApiResponse<User> updateUser(@PathVariable Long id, @RequestBody UserUpdateRequest request) {
        log.info("更新用户信息: id={}, request={}", id, request);
        User updatedUser = userService.updateUser(id, request);
        return ApiResponse.success(updatedUser);
    }
    
    @Operation(summary = "修改用户状态")
    @PutMapping("/users/{id}/status")
    public ApiResponse<User> updateUserStatus(@PathVariable Long id, @RequestBody Map<String, Boolean> request) {
        boolean enabled = request.getOrDefault("enabled", false);
        log.info("修改用户状态: id={}, enabled={}", id, enabled);
        User updatedUser = userService.updateUserStatus(id, enabled);
        return ApiResponse.success(updatedUser);
    }
    
    @Operation(summary = "重置用户密码")
    @PostMapping("/users/{id}/reset-password")
    public ApiResponse<String> resetPassword(@PathVariable Long id) {
        log.info("重置用户密码: id={}", id);
        String newPassword = userService.resetPassword(id);
        return ApiResponse.success(newPassword);
    }
} 